package com.zc.manager.network.initialize;

import com.zc.component.gateway.DeviceGateway;
import com.zc.component.gateway.DeviceGatewayManager;
import com.zc.manager.network.domain.IotDeviceGateway;
import com.zc.manager.network.enums.NetworkConfigState;
import com.zc.manager.network.service.IotDeviceGatewayService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.time.Duration;

/**
 * @author wangzheng
 * @since 1.0
 */
@Order(1)
@Component
@Slf4j
public class SyncDeviceGatewayState implements CommandLineRunner {

    private final IotDeviceGatewayService deviceGatewayService;

    private final DeviceGatewayManager deviceGatewayManager;

    private final Duration gatewayStartupDelay = Duration.ofSeconds(5);

    public SyncDeviceGatewayState(
            IotDeviceGatewayService deviceGatewayService,
            DeviceGatewayManager deviceGatewayManager
    ) {
        this.deviceGatewayService = deviceGatewayService;
        this.deviceGatewayManager = deviceGatewayManager;
    }

    @Override
    public void run(String... args) {
        log.debug("start device gateway in {} later", gatewayStartupDelay);



        Mono.delay(gatewayStartupDelay)
            .then(
                    Flux.fromIterable(deviceGatewayService.selectIotDeviceGatewayByStartState(NetworkConfigState.enabled.getValue()))
                            .map(IotDeviceGateway::getId)
                            .map(String::valueOf)
                            .flatMap(deviceGatewayManager::getGateway)
                            .flatMap(DeviceGateway::startup)
                            .onErrorContinue((err, obj) -> {
                                log.error(err.getMessage(), err);
                            })
                            .then()
            )
            .subscribe();
    }
}
